import base64
import json
import random
import string
import sys
import threading
import time

import pygame

cachePackage = []

message = {
    'to': [{"channelId": 1}],
    "package": cachePackage,
    "sendTime": time.time(),
    "progressId": 0
}


def id_generator(size=2, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))


def cacheInterval():
    global cachePackage
    packageId = 0
    while True:
        time.sleep(.1)
        _cachePackage = ""
        if cachePackage:
            _cachePackage = base64.b64encode(json.dumps(cachePackage).encode("utf-8"))
            packageId += 1
            _message = {
                'to': [{"channelId": 1}],
                "package": _cachePackage,
                "sendTime": time.time(),
                "packageId": packageId
            }

            print(base64.b64decode(_cachePackage))
        cachePackage = []


def main():
    global cachePackage
    pygame.init()
    size = (800, 600)
    screen = pygame.display.set_mode(size)

    threading.Thread(target=cacheInterval, daemon=True).start()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.MOUSEBUTTONUP:
                if not event.button == 0:
                    data = {"pos": event.pos, "btn": event.button}
                    cachePackage.append(data)
            if event.type == pygame.KEYUP:
                data = {'unicode': event.unicode, "key": event.key}
                cachePackage.append(data)


if __name__ == '__main__':
    main()
